package com.jdy.haoduoai.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.rx.util.async.Async;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

//import com.jdy.haoduoai.R;

/**
 * 购买记录
 * 
 * @author Administrator
 * 
 */
public class PurchaseRecordsActivity extends BaseActivity {

  @InjectView(id = R.id.purchase_record_listview)
  private ListView mPurchasedRecordList;

  private PurchaseRecordAdapter mPRAdapter;

  private List<PurchaseRecord> mPurchaseRecordsList;

  private LeUser mLeUser;

  @InjectView(id = R.id.valid_date_textview)
  private TextView mExpiredTextView;

  @InjectView(id = R.id.calendar_imageview)
  private ImageView mCalendarImageView;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.purchase_records_layout);
    setTitle("当前设备购买记录");
    if (Tools.isNotEmpty(LeConfig.expiredAt)) {
      mExpiredTextView.setText("会员到期时间：" + LeConfig.expiredAt);
    } else {
      mCalendarImageView.getViewTreeObserver().addOnGlobalLayoutListener(
          new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
              addEmptyView();
            }
          });
    }
    mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();
    if (mLeUser == null) {
      mLeUser = Tools.restoreLeUser();
    }
    initView();
    this.mUprightButton.setText("续费");
    this.mUprightButton.setTextColor(Color.WHITE);
    this.mUprightButton
        .setBackgroundResource(R.drawable.purchase_record_icon_background);
    this.mUprightButton.setPadding(20, 0, 20, 0);
    this.mUprightButton.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {

        v.startAnimation(mPressedAnimation);
        mPressedAnimation.setAnimationListener(new AnimationListener() {

          @Override
          public void onAnimationStart(Animation animation) {

          }

          @Override
          public void onAnimationRepeat(Animation animation) {

          }

          @Override
          public void onAnimationEnd(Animation animation) {

            Intent toMembershipPackages = new Intent(
                PurchaseRecordsActivity.this, MembershipCenterActivity.class);

            toMembershipPackages.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
                | Intent.FLAG_ACTIVITY_CLEAR_TOP);

            startActivity(toMembershipPackages);
            overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
          }
        });
      }
    });

  }

  private void addEmptyView() {
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    params.setMargins(0, mCalendarImageView.getHeight() + 40, 0, 0);
    params.addRule(RelativeLayout.RIGHT_OF, mCalendarImageView.getId());
    TextView emptyTextView = new TextView(this);
    emptyTextView.setGravity(Gravity.CENTER);
    emptyTextView.setLayoutParams(params);
    emptyTextView.setTextSize(16);
    emptyTextView.setText("暂无记录");
    ViewGroup parentview = (ViewGroup) mPurchasedRecordList.getParent();
    parentview.addView(emptyTextView, 1);

    mPurchasedRecordList.setEmptyView(emptyTextView);
  }

  private void initView() {
    mPurchaseRecordsList = new ArrayList<PurchaseRecord>();
    mPRAdapter = new PurchaseRecordAdapter(this, R.layout.purchase_record_item,
        mPurchaseRecordsList);
    mPurchasedRecordList.setAdapter(mPRAdapter);
    getPurchaseRecords();
  }

  private void getPurchaseRecords() {
    mPurchaseRecordsList.clear();

    showloading("");
    Async
        .start(new Func0<ResponseResult>() {

          @Override
          public ResponseResult call() {

            HashMap<String, Object> param_ = new HashMap<String, Object>();
            param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
            param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
            param_.put(HttpUtils.TAG_STATUS_I, "paid");

            return HttpUtils.startRequest(HttpUtils.API_URL
                + HttpUtils.GET_ORDER, param_, HttpUtils.TAG_GET_REQUEST);

          }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .filter(new Func1<ResponseResult, Boolean>() {

          @Override
          public Boolean call(ResponseResult arg0) {

            return arg0 != null && Tools.isNotEmpty(arg0) && arg0.isSuccess();
          }
        }).map(new Func1<ResponseResult, String>() {

          @Override
          public String call(ResponseResult arg0) {

            return arg0.data;
          }
        }).doOnCompleted(new Action0() {

          @Override
          public void call() {
            dismissLoading();
            mPRAdapter.notifyDataSetChanged();
          }
        }).subscribe(new Action1<String>() {

          @Override
          public void call(String arg0) {

            try {
              JSONArray jsonarray = new JSONArray(arg0);
              int i = 0;
              int size = jsonarray.length();
              for (; i < size; i++) {
                JSONObject jobject = jsonarray.getJSONObject(i);
                PurchaseRecord pr = new PurchaseRecord();
                pr.monthCount = jobject.getInt("product_period");
                pr.orderNo = jobject.getString("order_no");
                pr.title = "好多爱家长版会员 " + pr.monthCount + "个月";
                String dateString = jobject.getString("updated_at");

                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date d = f.parse(dateString);
                pr.purchaseTimestampMills = d.getTime();
                mPurchaseRecordsList.add(pr);
              }
            } catch (JSONException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            } catch (ParseException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          }
        });
  }

  // private void getPurchaseRecords() {
  // PurchaseRecord pr1 = new PurchaseRecord();
  // pr1.title = "小小班会员3个月";
  // pr1.monthCount = 3;
  // pr1.purchaseTimestampMills = System.currentTimeMillis();
  // pr1.calculateExpiredTimestamp(90);
  //
  // PurchaseRecord pr2 = new PurchaseRecord();
  // pr2.title = "小小班会员3个月";
  // pr2.monthCount = 3;
  // pr2.purchaseTimestampMills = System.currentTimeMillis();
  // pr2.calculateExpiredTimestamp(8);
  //
  // PurchaseRecord pr3 = new PurchaseRecord();
  // pr3.title = "小小班会员3个月";
  // pr3.monthCount = 3;
  // pr3.purchaseTimestampMills = System.currentTimeMillis();
  // pr3.calculateExpiredTimestamp(-8);
  //
  // mPurchaseRecordsList.add(pr1);
  // mPurchaseRecordsList.add(pr2);
  // mPurchaseRecordsList.add(pr3);
  // }

  public class PurchaseRecord {
    int recordType;

    String title;

    long monthCount;

    long purchaseTimestampMills;

    long expiredTimestampMills;

    String orderNo;

    // public void calculateExpiredTimestamp(int days) {
    // Date date = new Date(purchaseTimestampMills);
    // Calendar cal = Calendar.getInstance();
    // cal.setTime(date);
    // cal.add(Calendar.DATE, days);
    // expiredTimestampMills = cal.getTimeInMillis();
    // }

    public boolean isTenDaysBeforeExpired() {
      long diff = expiredTimestampMills - purchaseTimestampMills;
      long days = diff / (24 * 60 * 60 * 1000);
      return days <= 10;
    }

    public boolean isExpired() {
      long diff = expiredTimestampMills - purchaseTimestampMills;
      return diff <= 0;
    }
  }

  private class ViewHolder {
    @SuppressWarnings("unused")
    ImageView membershipIcon;
    TextView titleTextView;
    TextView timeLengthTextView;
    TextView purchaseTextView;
    TextView orderNoTextView;
    // TextView expireNotificationTextView;
    Button reNewButton;
  }

  public class PurchaseRecordAdapter extends ArrayAdapter<PurchaseRecord> {

    public List<PurchaseRecord> purchaseRecordsList;

    public PurchaseRecordAdapter(Context context, int resource,
        List<PurchaseRecord> objects) {
      super(context, resource, objects);
      // TODO Auto-generated constructor stub
      purchaseRecordsList = objects;
    }

    @SuppressWarnings("unused")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      ViewHolder holder;
      if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) PurchaseRecordsActivity.this
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        convertView = inflater.inflate(R.layout.purchase_record_item, parent,
            false);

        holder = new ViewHolder();

        // holder.membershipIcon = (ImageView) convertView
        // .findViewById(R.id.member_icon);

        holder.titleTextView = (TextView) convertView
            .findViewById(R.id.title_textview);
        holder.timeLengthTextView = (TextView) convertView
            .findViewById(R.id.timelength_textview);
        holder.purchaseTextView = (TextView) convertView
            .findViewById(R.id.purchase_time_textview);
        holder.orderNoTextView = (TextView) convertView
            .findViewById(R.id.order_no_textview);
        // holder.expireNotificationTextView = (TextView) convertView
        // .findViewById(R.id.expire_notification_textview);
        holder.reNewButton = (Button) convertView
            .findViewById(R.id.renew_button);

        convertView.setTag(holder);

      } else {
        holder = (ViewHolder) convertView.getTag();
      }

      PurchaseRecord purchaseRecord = purchaseRecordsList.get(position);

      switch (purchaseRecord.recordType) {
      }

      holder.titleTextView.setText(purchaseRecord.title);

      holder.orderNoTextView.setText("订单号:" + purchaseRecord.orderNo);

      holder.timeLengthTextView.setText("会员时长:" + purchaseRecord.monthCount
          + "个月");

      Date purchaseDate = new Date(purchaseRecord.purchaseTimestampMills);

      Date expireDate = new Date(purchaseRecord.expiredTimestampMills);

      Format formatter = new SimpleDateFormat("yyyy-MM-dd");

      Format moreDetailformatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

      String purchaseDateString = formatter.format(purchaseDate);

      String expireDateString = formatter.format(expireDate);

      final String detailExpireDateString = moreDetailformatter
          .format(expireDate);

      holder.purchaseTextView.setText("购买时间:" + purchaseDateString);

      // if (purchaseRecord.isExpired())
      // holder.expireNotificationTextView.setText("已经到期");
      // else {
      // holder.expireNotificationTextView.setText(expireDateString + "到期");
      // holder.expireNotificationTextView
      // .setOnClickListener(new View.OnClickListener() {
      //
      // @Override
      // public void onClick(View v) {
      //
      // showToast(PurchaseRecordsActivity.this, detailExpireDateString
      // + "到期");
      // }
      // });
      // }
      // ;

      if (purchaseRecord.isTenDaysBeforeExpired() || purchaseRecord.isExpired()) {
        holder.reNewButton.setVisibility(View.GONE);
        holder.reNewButton.setOnClickListener(new OnClickListener() {

          @Override
          public void onClick(View v) {

            v.startAnimation(mPressedAnimation);
            mPressedAnimation.setAnimationListener(new AnimationListener() {

              @Override
              public void onAnimationStart(Animation animation) {

              }

              @Override
              public void onAnimationRepeat(Animation animation) {

              }

              @Override
              public void onAnimationEnd(Animation animation) {

                Intent t = new Intent(PurchaseRecordsActivity.this,
                    MembershipCenterActivity.class);

                t.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
                    | Intent.FLAG_ACTIVITY_CLEAR_TOP);

                startActivity(t);
                overridePendingTransition(R.anim.push_left_in,
                    R.anim.push_left_out);
              }
            });
          }
        });
      } else {
        holder.reNewButton.setVisibility(View.GONE);
      }

      return convertView;
    }
  }

}
